# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.shortcuts import render_to_response
from django.contrib.auth.models import User

import datetime, random, sha
from django.shortcuts import render_to_response, get_object_or_404
from django.core.mail import send_mail
from forms import MyAuthForm
from blog.myblog.models import UserProfile, Destination
from blog.settings import SITE_ROOT

import xml.etree.ElementTree as ET


def index(request):
	if request.method == 'POST':
		form = AuthenticationForm(request.POST)
    		user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
    		if user is not None and user.is_active:
        		# Correct password, and the user is marked "active"
        		auth.login(request, user)
        		# Redirect to a success page.
        		return HttpResponseRedirect("/account/loggedin/")
		else:
        # Show an error page
       		#	return HttpResponseRedirect("/account/invalid/")
       			return render_to_response('login_form.html', {'form':form})
	else:
		form = AuthenticationForm()
		return render_to_response('login_form.html', {'form':form})

def create_user_form(request):
	if request.method == 'POST':
		form = UserCreationForm(request.POST)
		#if form.clean_username():
		#	form.save()
		if form.is_valid():
			cd = form.cleaned_data
			form.save()
			#u = User.objects.get(username=cd['username'])
		#	if u:
		#		return HttpResponse (u.get_profile().username)
		#	else:
		#		return HttpResponse ("Error!")
			return HttpResponse("Successfully saved the user!")
		else:
			return render_to_response('create_user_form.html', {'form':form})
	else:
		form = UserCreationForm()
		return render_to_response('create_user_form.html', {'form':form})

def user_logged_in(request):
	if request.user.is_authenticated :
		#Proceed
		return HttpResponse("User has logged in .. now display the contents and other options")
	else:
		return HttpResponseRedirect("/blog")
	

def view_dests(request):
	fd = open(SITE_ROOT +'/cycle/view_dests.htm')
	str = fd.read()
	fd.close()
	return HttpResponse(str)

def serve_dest_xml(request):
	return HttpResponse('<destinations> <!-- Dont use copy and paste on this XML file, use "View Source" or "Save As" What the browser displays is *interpreted* XML, not XML source. --> <destination dest-id="1" lat="12.9792167688559" lng="77.6572036743164" dest-name="CV Raman Nagar"> <dest-times> <dest-time>800</dest-time> <dest-time>900</dest-time> </dest-times> </destination> <destination dest-id="2" lat="12.975620315224319" lng="77.60544776916504" dest-name="MG road"> <dest-times> <dest-time>900</dest-time> </dest-times> </destination> <destination dest-id="3" lat="12.837577694225002" lng="77.67127990722656" dest-name="Electronics city"> <dest-times> <dest-time>800</dest-time> <dest-time>830</dest-time> <dest-time>900</dest-time> </dest-times> </destination> <destination dest-id="4" lat="12.957051750634836" lng="77.59274482727051" dest-name="Kengal Hanumanthaiah road"> <dest-times> <dest-time>1000</dest-time> </dest-times> </destination> </destinations>')
	dests = Destination.objects.all()
	
	root = ET.Element("destinations")

	for dest in dests :
		lnd = dest.landmark
		destination = ET.SubElement(root, "destination")
		destination.set("dest-id",str(lnd.id))
		destination.set("lat", lnd.lat)
		destination.set("lng", lnd.lng)
		destination.set("dest-name", lnd.name)
		dest_times = ET.SubElement(destination, "dest-times")
		times = dest.times.split(",")
		for time in times:
			dest_time = ET.SubElement(dest_times, "dest-time")
			dest_time.text = time

	xml_str = ET.tostring(root)

	return HttpResponse(xml_str)
		
		
def view_dest_routes(request, destid, time):
	return HttpResponse("you gave me %s %s"% (destid, time))	

def serve_dest_routes_xml(request, destid, time):
	fd = open(SITE_ROOT + '/cycle/dest_routes.xml')
	str = fd.read()
	fd.close()
	return HttpResponse(str, mimetype='text/xml')

#Add an entry to the dest table, given a dest location, and time
#Add the entry to the landmark table too if appropriate
def add_dest(request):
	request.POST["lat"]
	request.POST["lng"]
	request.POST["dest_time"]
	return None

#Add a route
def add_route(request):
	return None

def submit_route(request):
	return HttpResponse("Route successfully submitted!\n")

